<template>
  <common-layout title="部门管理">
    <template #header-buttons>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增部门
      </el-button>
    </template>

    <template #search-form>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="部门编码" style="width: 260px;">
          <el-input v-model="searchForm.departmentCode" placeholder="请输入部门编码"></el-input>
      </el-form-item>
      <el-form-item label="部门名称" style="width: 260px;">
        <el-input v-model="searchForm.departmentName" placeholder="请输入部门名称"></el-input>
      </el-form-item>
      <el-form-item label="状态" style="width: 260px;">
        <el-select v-model="searchForm.status" placeholder="请选择状态">
          <el-option label="全部" value=""></el-option>
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="width: auto;">
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="resetSearch">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>
    </template>

    <template #data-content>
    <!-- 部门列表 -->
    <el-table :data="departments" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="departmentCode" label="部门编码" width="120" />
        <el-table-column prop="name" label="部门名称" width="180" />
        <el-table-column prop="parentName" label="上级部门" width="180" />
        <el-table-column prop="description" label="部门描述" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="handleStatusChange(scope.row)">
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </template>

    <!-- 新增/编辑部门对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="上级部门" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择上级部门">
            <el-option :value="0" label="无" />
            <el-option v-for="dept in departments" :key="dept.id" :value="Number(dept.id)" :label="dept.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入部门描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </common-layout>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElIcon } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { apiRequest } from '@/utils/apiRequest'
import CommonLayout from '../components/CommonLayout.vue'

// 部门列表数据
const departments = ref([])
// 搜索表单
const searchForm = reactive({
  departmentCode: '',
  departmentName: '',
  status: ''
})

// 加载状态
const loading = ref(false)
// 分页大小
const pageSize = ref(10)

// 当前查看的部门
const currentDepartment = ref(null)
// 查看详情对话框
const detailDialogVisible = ref(false)

// 获取部门列表
const getDepartments = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await apiRequest.get('/api/Departments', { params })
    console.log('API响应:', response)
    // 检查数据格式，处理Entity Framework Core的序列化格式
    let departmentsData = []
    if (response.data && response.data.items && Array.isArray(response.data.items)) {
      departmentsData = response.data.items
      total.value = response.data.total || 0
    } else if (Array.isArray(response.data)) {
      departmentsData = response.data
      total.value = departmentsData.length
    } else if (response.data && response.data.$values && Array.isArray(response.data.$values)) {
      departmentsData = response.data.$values
      console.log('使用$values属性作为部门数据')
      total.value = departmentsData.length
    } else {
      console.error('API返回的数据不是数组或不包含$values属性:', response.data)
      ElMessage.error('获取部门列表失败: 数据格式不正确')
      return
    }
    
    // 转换后端数据结构以匹配前端需求
    departments.value = departmentsData.map(dept => ({
      id: Number(dept.id),
      departmentCode: dept.departmentCode || '',
      name: dept.departmentName,
      parentId: dept.parentDepartmentId !== null ? Number(dept.parentDepartmentId) : 0,
      parentName: dept.parentDepartment?.departmentName || '无',
      description: dept.description,
      status: dept.status ? 1 : 0,
      createTime: dept.createTime
    }))
  } catch (error) {
    ElMessage.error('获取部门列表失败: ' + error.message)
    console.error('Failed to fetch departments:', error)
  } finally {
    loading.value = false
  }
}

const currentPage = ref(1)
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('新增部门')
const formRef = ref(null)
const form = reactive({
  id: 0,
  name: '',
  parentId: 0,
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 20, message: '部门名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '部门描述最多 200 个字符', trigger: 'blur' }
  ]
}

// 新增部门
const handleAdd = () => {
  dialogTitle.value = '新增部门'
  form.id = 0
  form.name = ''
  form.parentId = 0
  form.description = ''
  dialogVisible.value = true
}

// 查看详情
const handleView = (row) => {
  currentDepartment.value = { ...row }
  detailDialogVisible.value = true
}

// 编辑部门
const handleEdit = (row) => {
  dialogTitle.value = '编辑部门'
  form.id = Number(row.id)
  form.name = row.name
  form.parentId = row.parentId !== null ? Number(row.parentId) : 0
  form.description = row.description
  dialogVisible.value = true
}

// 状态切换
const handleStatusChange = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  ElMessageBox.confirm(
    `确定要${statusText}部门 ${row.name} 吗？`,
    '状态确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        await apiRequest.patch(`/api/Departments/${row.id}/status`, { status: newStatus })
        ElMessage({ message: `部门${statusText}成功`, type: 'success' })
        // 重新获取部门列表
        getDepartments()
      } catch (error) {
        ElMessage.error(`${statusText}部门失败: ` + error.message)
        console.error(`Failed to ${statusText} department:`, error)
      }
    })
    .catch(() => {
      ElMessage({ message: '已取消操作', type: 'info' })
    })
}

// 提交表单
const handleSubmit = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 调用真实API
      if (form.id === 0) {
  // 新增
  try {
    // 转换前端数据结构以匹配后端需求
    const deptData = {
      departmentName: form.name,
      parentDepartmentId: form.parentId === 0 ? null : form.parentId,
      description: form.description,
      status: true
    }
    const newDept = await apiRequest.post('/api/Departments', deptData)
    ElMessage({ message: '部门添加成功', type: 'success' })
    // 重新获取部门列表
    getDepartments()
  } catch (error) {
    ElMessage.error('添加部门失败: ' + error.message)
    console.error('Failed to add department:', error)
  }
} else {
  // 编辑
  try {
    // 转换前端数据结构以匹配后端需求
    const deptData = {
      id: form.id,
      departmentName: form.name,
      parentDepartmentId: form.parentId === 0 ? null : form.parentId,
      description: form.description,
      status: true
    }
    await apiRequest.put(`/api/Departments/${form.id}`, deptData)
    ElMessage({ message: '部门更新成功', type: 'success' })
    // 重新获取部门列表
    getDepartments()
  } catch (error) {
    ElMessage.error('更新部门失败: ' + error.message)
    console.error('Failed to update department:', error)
  }
}
  dialogVisible.value = false
    }
  })
}

// 删除部门
const handleDelete = (row) => {
  // 检查是否有子部门
  const hasChildren = departments.value.some(dept => dept.parentId === row.id)
  if (hasChildren) {
    ElMessage({ message: '该部门有子部门，无法删除', type: 'error' })
    return
  }

  ElMessageBox.confirm(
    `确定要删除部门 ${row.name} 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      // 调用真实API
  try {
    await apiRequest.delete(`/api/Departments/${row.id}`)
    ElMessage({ message: '部门删除成功', type: 'success' })
    // 重新获取部门列表
    getDepartments()
  } catch (error) {
    ElMessage.error('删除部门失败: ' + error.message)
    console.error('Failed to delete department:', error)
  }
    })
    .catch(() => {
      ElMessage({ message: '已取消删除', type: 'info' })
    })
}

const handleSizeChange = (size) => {
  console.log(`每页 ${size} 条`)
}

const handleCurrentChange = (current) => {
  console.log(`当前页: ${current}`)
}

// 搜索部门
const handleSearch = async () => {
  try {
    // 构建搜索参数
    const params = {
      ...searchForm,
      page: 1,
      pageSize: 10
    }

    const response = await apiRequest.get('/api/Departments/search', { params })
    console.log('搜索响应:', response)

    // 处理搜索结果
    let departmentsData = []
    if (Array.isArray(response.data)) {
      departmentsData = response.data
    } else if (response.data && response.data.$values && Array.isArray(response.data.$values)) {
      departmentsData = response.data.$values
    } else {
      console.error('搜索返回的数据格式不正确:', response.data)
      ElMessage.error('搜索部门失败: 数据格式不正确')
      return
    }

    // 转换后端数据结构
    departments.value = departmentsData.map(dept => ({
      id: Number(dept.id),
      departmentCode: dept.departmentCode || '',
      name: dept.departmentName,
      parentId: dept.parentDepartmentId !== null ? Number(dept.parentDepartmentId) : 0,
      parentName: dept.parentDepartment?.departmentName || '无',
      description: dept.description,
      status: dept.status ? 1 : 0,
      createTime: dept.createTime
    }))
    total.value = departments.value.length
  } catch (error) {
    ElMessage.error('搜索部门失败: ' + error.message)
    console.error('Failed to search departments:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.departmentCode = ''
  searchForm.departmentName = ''
  searchForm.status = ''
  getDepartments()
}

// 页面加载时获取部门列表
onMounted(() => {
  getDepartments()
})
</script>

<style scoped>
/* 原有样式被CommonLayout组件样式替代 */

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.el-textarea {
  min-height: 100px;
}
</style>